(function (mui, $) {
	
var _Data = {};

// 普通页面跳转
$('body').delegate('[data-url]', 'tap', function () {
	app.open($(this).attr('data-url'));
});

// 退出登录
$('.btn-logout').on('tap', function () {
	localStorage.removeItem('token');
	localStorage.removeItem('member');
	app.open('member.login.html');
	
	plus.webview.getWebviewById('member.html').evalJS('member.refresh()');
	setTimeout(function () {
		plus.webview.currentWebview().close();
	}, 200);
});

// 选择头像
$('.btn-pick-image').on('tap', function () {
	var btns = [{title:"拍照" }, {title: "从手机相册选择"}];
	
	plus.nativeUI.actionSheet({
		title   : "选择照片",
		cancel  : "取消",
		buttons : btns
	}, function(btn) {
		switch (btn.index) {
			case 0:
				break;
			case 1:
				getFromCamera();
				break;
			case 2:
				getFromGallery();
				break;
			default:
				break
		}
	});
});

function getFromCamera () {
	var camera = plus.camera.getCamera();
	camera.captureImage(function(e) {
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			cutter({'path':entry.toLocalURL(), 'name':entry.name});
		}, function(e) {
			plus.nativeUI.toast("读取拍照文件错误：" + e.message);
		});
	}, function(res) {
		plus.nativeUI.toast(res);
	}, {
		filename: "_doc/head.jpg"
	});
}

function getFromGallery () {
	plus.gallery.pick(function(a) {
		plus.io.resolveLocalFileSystemURL(a, function(entry) {
			cutter({'path':entry.toLocalURL(), 'name':entry.name});
		}, function(e) {
			app.log("读取本地相册错误：" + e.message);
		});
	}, function(a) {}, {
		filter: "image"
	});
};

function cutter (image) {
	upload(image);
}

function upload (image) {
	app.log('上传数据：' + JSON.stringify(image));
	plus.nativeUI.showWaiting('正在处理...');
	function _cb (result, status) {
		var res = result.responseText;
		plus.nativeUI.closeWaiting();
		
		try { res = JSON.parse(res); } catch (e) { status = 404 }
		
		if (status == 200) {
			//plus.nativeUI.toast('上传文件成功');
			app.log('上传结果：' + JSON.stringify(res));
			append(res);
		} else {
			app.log('上传头像失败：' + result.responseText);
			plus.nativeUI.toast('上传图片失败');
		}
	}
	var task = plus.uploader.createUpload(app.url('Files/Upload/appUpload'), { method:"POST",blocksize:204800,priority:100 }, _cb);
	task.addFile(image.path, {'name':image.name});
	
	task.addData('thumb', image);
	task.addData('token', app.store('token'));
	task.addData('action', 'uploadimage');
	
	task.start();
}

function append (image) {
	app.log(image);
	var path = image.data.pop();
	set({'avatar':path}, function (res) {
		$('.touxiang img').attr('src', app.avatar(path));
	});
}

// 更新用户信息
function set (data, cb) {
	plus.nativeUI.showWaiting();
	app.log('更新用户资料：', data);
	$.ajax({
		'dataType' : 'json',
		'type'     : 'post',
		'url'      : app.url('App/Member/Index/update'),
		'data'     : {'token':app.store('token'), 'data':data}
	})
	.fail(function (res) {
		app.log('更新用户信息失败：', res);
		app.toast('更新用户信息失败');
		plus.nativeUI.closeWaiting();
	})
	.done(function (res) {
		app.log('更新用户信息：', res);
		plus.nativeUI.closeWaiting();
		
		if (500 == res.code) { app.toast('你还未登录'); return; }
		if (300 == res.code) { app.toast(res.msg); return; }
		if (200 != res.code) { app.toast('请求失败'); return; }
		if (res.msg) { app.toast(res.msg); }
		
		app.store('member', res.data);
		plus.webview.getWebviewById('member.html').evalJS('member.refresh('+JSON.stringify(res.data)+')');
		cb && cb(res);
	})
	;
}

//点击昵称一整行 弹出 修改昵称对话框 昵称去前后空格
$("#promptBtn").on('tap', function(e) {
	var btnArray = ['取消', '确定'];
	mui.prompt('请输入昵称：', $("#info-name").text(), '提示!', btnArray, function(e) {
		var v = e.value.trim();
		if (e.index == 0) {
			
		} else if (0 == v.length || v.length > 15) {
			app.toast('昵称为1到15个字');
		} else {
			set({'nicname':e.value}, function (res) {$("#info-name").text(e.value);});
		}
	})
});

//点击性别一整行 弹出 修改选择性别对话框
$("#confirmBtn").on('tap', function() {
	var ary = ['女', '男'];
	mui.confirm('请选择性别', '提示！', ary, function(e) {
		set({'sex':e.index+1}, function () {$("#info-sex").text(ary[e.index]);});
	})
});
//点击选择所在城市
mui.ready(function() {
	var picker = new mui.PopPicker({layer:2});
	picker.setData(cityData);
	$("#btn-area").on('tap', function() {
		picker.show(function(items) {
			$("#cityResult").text(items[0].text + " " + items[1].text);
		});
	});
	
	var member = app.store('member');
	$('.btn-pick-image img').attr('src', app.avatar(member.avatar));
	$('#info-name').text(member.nicname || '');
	$('#info-sex').text(['女', '男'][member.sex]);
	$('.birth').text(member.create_time);
});

})(mui, $);